package com.fc.remoting.util;

import java.net.SocketAddress;

import com.fc.remoting.logger.RemotingLogger;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

public class ChannelUtil {
	
	/**
	 * 解析地址
	 * @param channel
	 * @return
	 */
	public static String parseChannelRemoteAddr(final Channel channel) {
        if (null == channel) {
            return "";
        }
        final SocketAddress remote = channel.remoteAddress();
        final String addr = remote != null ? remote.toString() : "";

        if (addr.length() > 0) {
            int index = addr.lastIndexOf("/");
            if (index >= 0) {
                return addr.substring(index + 1);
            }
            return addr;
        }

        return "";
    }
	
	/**
	 * 关闭channel链接
	 * @param channel
	 */
	public static void closeChannel(Channel channel) {
		final String addrRemote = parseChannelRemoteAddr(channel);
		channel.close().addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				RemotingLogger.getLogger().info(
						"closeChannel: close the connection to remote address[{}] result: {}", addrRemote,
						future.isSuccess());
			}
		});
	}

}
